import os
import urllib.request
import json
import xlwings
import pandas
import time


# 将抽卡信息的字典列表输出至桌面Excel
def streamOut(recordDic):
    print('开始存入Excel表格')
    app = xlwings.App(visible=False, add_book=False)
    workbook = app.books.add()
    for key, value in recordDic.items():
        worksheet = workbook.sheets.add(key)
        worksheet['A1'].value = value
        worksheet.range('K2').expand('down').api.NumberFormat = "0"  # 将ID列改为全部显示
        worksheet.autofit()
    try:
        filePath = os.path.join(os.path.expanduser('~'), "Desktop") + r'\抽卡记录' + str(time.time()) + '.xlsx'
        workbook.save(filePath)
    except IOError:
        print('创建失败')
    else:
        print('已创建文件' + filePath)
    finally:
        workbook.close()
        app.quit()


# 根据URL获取抽卡信息并返回一个字典列表
def getRecords(Url):
    requestCode = '&game_biz=hk4e_cn&page=1&size=20'
    recordsDic = dict()
    gacha_types = dict({'301': '限定池1', '302': '武器池', '200': '常驻池', '400': '限定池2'})
    for gacha_type, gacha_name in gacha_types.items():
        endCode = 0
        recordIfo = pandas.DataFrame(
            columns=['uid', '祈愿类型', 'item_id', 'count', '时间', '名称', 'lang', '类别', '星级',
                     'id'])  # 建立空字典,存放抽卡记录
        flag = True
        while flag:
            response = urllib.request.urlopen(
                Url + requestCode + '&end_id=' + str(endCode) + '&gacha_type=' + gacha_type)
            html = response.read()
            data = json.loads(html)['data']['list']
            if len(data) != 0:
                for item in data:
                    recordIfo = recordIfo.append(
                        {'uid': item['uid'], '祈愿类型': gacha_types[item['gacha_type']], 'item_id': item[
                            'item_id'], 'count': item['count'], '时间': item['time'], '名称': item['name'],
                         'lang': item[
                             'lang'], '类别': item['item_type'], '星级': item['rank_type'], 'id': "'" + item['id']},
                        ignore_index=True)
                    endCode = item['id']
            flag = len(data) == 20
        recordsDic[str(gacha_name)] = recordIfo
    print('已完成数据爬取')
    return recordsDic


if __name__ == '__main__':
    api_url = 'https://hk4e-api.mihoyo.com/event/gacha_info/api/getGachaLog?'
    url = input('输入抽卡界面的url:')
    try:
        api_url += url.split('index.html?')[1].split('&game_biz=hk4e_cn')[0]
    except IndexError:
        print('URL输入错误')
    else:
        print('URL解析成功，开始爬取数据')
        streamOut(getRecords(api_url))
    input()
